package neu.tour.support;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by lijialin on 4/19/16.
 */
public class HttpConnectionUtil {

    private static final String GET = "GET";
    private static final String POST = "POST";
    private static final String PUT = "PUT";
    private static final String PATCH = "PATCH";
    private static final String DELETE = "DELETE";
    public static  String result = "";

    public static final String SERVERURL = "http://120.27.118.23:5678/cross/";
    public static final String PLACEURL = SERVERURL+"place/";


    private static String prepareParam(Map<String,Object> paramMap){
        StringBuffer sb = new StringBuffer();
        if(paramMap.isEmpty()){
            return "" ;
        }else{
            for(String key: paramMap.keySet()){
                String value = (String)paramMap.get(key);
                if(sb.length()<1){
                    sb.append(key).append("=").append(value);
                }else{
                    sb.append("&").append(key).append("=").append(value);
                }
            }
            return sb.toString();
        }
    }

    public static void doGet(String urlStr, Map<String,Object> paramMap) throws Exception{
        String paramStr = prepareParam(paramMap);
        if(paramStr == null || paramStr.trim().length()<1){

        }else{
            urlStr +="?"+paramStr;
        }
        URL url = new URL(urlStr);
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();
        conn.setRequestMethod(GET);
        conn.setRequestProperty("Content-Type","text/html; charset=UTF-8");
        conn.connect();
        if (conn.getResponseCode() != 200) {
            throw new RuntimeException("request failed");
        } else {
            changeInputToString(conn);
        }
    }

    private static void changeInputToString(HttpURLConnection conn) throws Exception{
        BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line;
        while ((line = br.readLine()) != null) {
            result += line;
        }
        br.close();
    }

    public static void sendRequest(String urlStr, Map<String,Object> paramMap, String method) throws Exception{
        URL url = new URL(urlStr);
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();
        conn.setRequestMethod(method);
        String paramStr = prepareParam(paramMap);
        conn.setDoInput(true);
        conn.setDoOutput(true);
        OutputStream os = conn.getOutputStream();
        os.write(paramStr.toString().getBytes("utf-8"));
        os.close();

        changeInputToString(conn);
    }

    public static void doPost(String urlStr,Map<String,Object> paramMap) throws Exception{
        sendRequest(urlStr, paramMap, POST);
    }

    public static void doPut(String urlStr,Map<String,Object> paramMap) throws Exception{
        sendRequest(urlStr, paramMap, PUT);
    }

    public static void doPatch(String urlStr,Map<String,Object> paramMap) throws Exception{
        sendRequest(urlStr, paramMap, PATCH);
    }

    public static void doDelete(String urlStr) throws Exception{
        URL url = new URL(urlStr);
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod(DELETE);

        if(conn.getResponseCode() == 204){//204 means server return nothing
//            changeInputToString(conn);
            result = "success";
        }else{
            System.out.println(conn.getResponseCode());
        }
    }

    public static ArrayList<HashMap<String, Object>> decodeJsonToPoint(String jsonStr)
            throws JSONException {
        JSONArray jsonArray = null;
        ArrayList<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();
        jsonArray = new JSONArray(jsonStr);
//        System.out.println("asdf json.length = " + jsonArray.length());
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            HashMap<String, Object> map = new HashMap<String, Object>();
            map.put("id", jsonObject.getInt("id"));
            map.put("name", jsonObject.getString("name"));
            map.put("longitude", jsonObject.getString("longitude"));
            map.put("latitude", jsonObject.getString("latitude"));
            map.put("cross_pictures", jsonObject.getString("cross_pictures"));
            list.add(map);
        }
        return list;
    }




    public static ArrayList<HashMap<String, Object>> decodeCrossPicturesJsonToPoint(String jsonStr)
            throws JSONException {
        JSONArray jsonArray = null;
        ArrayList<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();
        jsonArray = new JSONArray(jsonStr);
        System.out.println("asdf json.length = " + jsonArray.length());
        for (int i = 0; i < jsonArray.length(); i++) {
            final JSONObject jsonObject = jsonArray.getJSONObject(i);
            final HashMap<String, Object> map = new HashMap<String, Object>();
            map.put("id", jsonObject.getInt("id"));
            map.put("title", jsonObject.getString("title"));
            map.put("picture", jsonObject.getString("picture"));
            map.put("longitude", jsonObject.getString("longitude"));
            map.put("latitude", jsonObject.getString("latitude"));
            map.put("detail_title", jsonObject.getString("detail_title"));
            map.put("detail_url", jsonObject.getString("detail_url"));
            list.add(map);
        }
        return list;
    }


    public static Bitmap returnBitMap(final String url){
        final Bitmap[] bitmap = new Bitmap[1];
        new Thread(){
            public void run(){
                try{
                    URL myFileUrl = new URL(url);
                    HttpURLConnection conn = (HttpURLConnection) myFileUrl
                            .openConnection();
                    conn.setDoInput(true);
                    conn.connect();
                    InputStream is = conn.getInputStream();
                    bitmap[0] = BitmapFactory.decodeStream(is);
                    is.close();
                } catch(IOException e) {
                    e.printStackTrace();
                }

            }
        }.start();
        return bitmap[0];
    }

}
